package com.kku;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DietplannerPlugin extends Activity {
	DietplannerPlugin() {
	};

	public static Context MyContext = null;
	private Context MAIN_CONTEXT = null;
	private JSONObject WaitResult = null;
	static final int ADD_FOOD = 1;
	static final int ADD_TRAINING = 2;
	static final int ADD_PICTURE = 3;
	static final int GET_PICTURE = 4;
	static final int MODIFY_PICTURE = 5;
	static final int ADD_POPUP_LIST = 6;
	static final int ASYNC_DIALOG = 10;

	public void setContext(Context c) {
		MyContext = this;
		MAIN_CONTEXT = c;
	}

	public JSONObject popupAddFood() {
		return WaitPopup(ADD_FOOD, "");
	}

	public JSONObject popupAddTraining() {
		return WaitPopup(ADD_TRAINING, "");
	}

	public JSONObject popupAddPicture() {
		return WaitPopup(ADD_PICTURE, "");
	}

	public JSONObject popupModifyPicture(String location) {
		return WaitPopup(MODIFY_PICTURE, location);
	}
	
	public JSONObject popupAddList(String location) {
		return WaitPopup(ADD_POPUP_LIST, location);
	}

	public void aSyncDialog(final String jsonArgs) {
		final JSONObject jsonObj;
		String context;
		try {
			jsonObj = (JSONObject) new JSONTokener(jsonArgs).nextValue();

			context = jsonObj.getString("context");

			SharedPreferences prefs = MAIN_CONTEXT.getSharedPreferences("getDialogData", MAIN_CONTEXT.MODE_PRIVATE);
			boolean CheckContext = prefs.getBoolean(context, true);
			if (CheckContext) {
				new Thread(new Runnable() {
					public void run() {
						Message msg = mhandler.obtainMessage();
						msg.what = ASYNC_DIALOG;
						msg.obj = jsonObj;
						mhandler.sendMessage(msg);
					}
				}).start();
			}
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public synchronized JSONObject WaitPopup(int param, final String str) {
		try {
			WaitResult = new JSONObject();
			switch (param) {
			case ADD_FOOD:
				new Thread(new Runnable() {
					public void run() {
						Message msg = mhandler.obtainMessage();
						msg.what = ADD_FOOD;
						mhandler.sendMessage(msg);
					}
				}).start();
				break;
			case ADD_TRAINING:
				new Thread(new Runnable() {
					public void run() {
						Message msg = mhandler.obtainMessage();
						msg.what = ADD_TRAINING;
						mhandler.sendMessage(msg);
					}
				}).start();
				break;
			case ADD_PICTURE:
				new Thread(new Runnable() {
					public void run() {
						Message msg = mhandler.obtainMessage();
						msg.what = ADD_PICTURE;
						mhandler.sendMessage(msg);
					}
				}).start();
				break;
			case MODIFY_PICTURE:
				new Thread(new Runnable() {
					public void run() {
						Message msg = mhandler.obtainMessage();
						msg.what = MODIFY_PICTURE;
						msg.obj = str;
						mhandler.sendMessage(msg);
					}
				}).start();
				break;
			case ADD_POPUP_LIST:
				new Thread(new Runnable() {
					public void run() {
						Message msg = mhandler.obtainMessage();
						msg.what = ADD_POPUP_LIST;
						msg.obj = str;
						mhandler.sendMessage(msg);
					}
				}).start();
				break;
			default:
				break;
			}
			DietplannerPlugin.this.wait();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return WaitResult;
		}
	}

	Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ASYNC_DIALOG:
				try {
					showaSyncDialog(msg.obj);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case ADD_FOOD:
				showAddFood();
				break;
			case ADD_TRAINING:
				showAddTraining();
				break;
			case ADD_PICTURE:
				showAddPicture();
				break;
			case MODIFY_PICTURE:
				showModifyPicture((String) msg.obj);
				break;
			case ADD_POPUP_LIST:
				showPopupList((String) msg.obj);
				break;

			default:
				break;
			}
		}
	};

	public void showaSyncDialog(Object obj) throws JSONException {
		JSONObject jsonObj = (JSONObject) obj;
		final Dialog aSyncDialog = new Dialog(MAIN_CONTEXT);
		aSyncDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		aSyncDialog.setContentView(R.layout.async_dialog_popup);
		aSyncDialog.setCancelable(true);

		aSyncDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

		TextView title = (TextView) aSyncDialog.findViewById(R.id.dialog_title);
		title.setText(jsonObj.getString("title"));
		TextView content = (TextView) aSyncDialog.findViewById(R.id.content_label);
		content.setText(jsonObj.getString("content"));
		Button positiveBtn = (Button) aSyncDialog.findViewById(R.id.positiveBtn);

		final String context = jsonObj.getString("context");

		positiveBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				aSyncDialog.dismiss();
				CheckBox checkBox = (CheckBox) aSyncDialog.findViewById(R.id.dialog_checkbox);
				boolean checkDialog = checkBox.isChecked();
				if (checkDialog) {
					SharedPreferences prefs = MAIN_CONTEXT.getSharedPreferences("getDialogData", MAIN_CONTEXT.MODE_PRIVATE);
					SharedPreferences.Editor editor = prefs.edit();
					editor.putBoolean(context, false);
					editor.commit();
				}
			}
		});

		aSyncDialog.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				aSyncDialog.dismiss();
			}
		});

		aSyncDialog.show();
	}

	public void pluginInterface(JSONObject data) {
		synchronized (DietplannerPlugin.this) {
			DietplannerPlugin.this.notify();
			WaitResult = data;
		}
	}

	public void showAddPicture() {
		final Dialog AddPicture = new Dialog(MAIN_CONTEXT);
		AddPicture.requestWindowFeature(Window.FEATURE_NO_TITLE);
		AddPicture.setContentView(R.layout.picture_popup);
		AddPicture.setCancelable(true);

		AddPicture.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

		Button CameraBtn = (Button) AddPicture.findViewById(R.id.getCameraBtn);
		Button AlbumBtn = (Button) AddPicture.findViewById(R.id.getAlbumBtn);

		CameraBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				AddPicture.dismiss();
				((DietplannerActivity) MAIN_CONTEXT).resultCamera(ADD_PICTURE);
			}
		});
		AlbumBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				AddPicture.dismiss();
				((DietplannerActivity) MAIN_CONTEXT).resultAlbum(GET_PICTURE);
			}
		});

		AddPicture.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				AddPicture.dismiss();
				synchronized (DietplannerPlugin.this) {
					DietplannerPlugin.this.notify();
					WaitResult = null;
				}
			}
		});

		AddPicture.show();
	}

	public void showModifyPicture(String location) {

		final Dialog ModifyPicture = new Dialog(MAIN_CONTEXT);
		ModifyPicture.requestWindowFeature(Window.FEATURE_NO_TITLE);
		ModifyPicture.setContentView(R.layout.modify_picture_popup);
		ModifyPicture.setCancelable(true);

		ModifyPicture.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

		Button getPicture = (Button) ModifyPicture.findViewById(R.id.getPicture);
		ImageView image = (ImageView) ModifyPicture.findViewById(R.id.my_picture);

		File targetFile = new File(location);
		FileInputStream target;
		Bitmap bm = null;
		try {
			target = new FileInputStream(targetFile);
			Bitmap originalImage = BitmapFactory.decodeStream(target);// 얻어온 데이터
																		// Bitmap
																		// 에저장

			int iHeight = originalImage.getHeight();
			int iWidth = originalImage.getWidth();

			while (iHeight > 680 || iWidth > 680) {
				iHeight = iHeight * 3 / 4;
				iWidth = iWidth * 3 / 4;
			}

			bm = Bitmap.createScaledBitmap(originalImage, iWidth, iHeight, false);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (bm != null) {
			image.setImageBitmap(bm);
		}

		getPicture.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ModifyPicture.dismiss();
				showAddPicture();
			}
		});

		ModifyPicture.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				ModifyPicture.dismiss();
				synchronized (DietplannerPlugin.this) {
					DietplannerPlugin.this.notify();
					WaitResult = null;
				}
			}
		});

		ModifyPicture.show();
	}

	public void showPopupList(String jsonArgs) {
		
		JSONArray jsonArray = new JSONArray();
		try {
			jsonArray = new JSONArray(jsonArgs);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		DietListAdapter adapter = new DietListAdapter(MAIN_CONTEXT, R.layout.popup_list_row, jsonArray);
		
		final Dialog popupList = new Dialog(MAIN_CONTEXT);
		popupList.requestWindowFeature(Window.FEATURE_NO_TITLE);
		popupList.setContentView(R.layout.popup_list);
		popupList.setCancelable(true);

		popupList.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

		ListView popupListView = (ListView) popupList.findViewById(R.id.popup_list_row);

		popupListView.setAdapter(adapter);
		popupListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				popupList.dismiss();
				synchronized (DietplannerPlugin.this) {
					try {
						WaitResult.put("position", position);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					DietplannerPlugin.this.notify();
				}
			}
		});
		
		popupList.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				popupList.dismiss();
				synchronized (DietplannerPlugin.this) {
					DietplannerPlugin.this.notify();
					WaitResult = null;
				}
			}
		});

		popupList.show();
	}

	public void showAddTraining() {
		final Dialog AddTraining = new Dialog(MAIN_CONTEXT);
		AddTraining.requestWindowFeature(Window.FEATURE_NO_TITLE);
		AddTraining.setContentView(R.layout.add_traning_popup);
		AddTraining.setCancelable(true);

		AddTraining.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

		Button positiveBtn = (Button) AddTraining.findViewById(R.id.positiveBtn);

		positiveBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				AddTraining.dismiss();
				TextView title = (TextView) AddTraining.findViewById(R.id.traningname_text);
				TextView kcal = (TextView) AddTraining.findViewById(R.id.traningkcal_text);
				synchronized (DietplannerPlugin.this) {
					DietplannerPlugin.this.notify();
					try {
						WaitResult.put("title", title.getText());
						WaitResult.put("kcal", kcal.getText());
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});

		AddTraining.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				AddTraining.dismiss();
				synchronized (DietplannerPlugin.this) {
					DietplannerPlugin.this.notify();
					WaitResult = null;
				}
			}
		});

		AddTraining.show();
	}

	public void showAddFood() {
		final Dialog AddFood = new Dialog(MAIN_CONTEXT);
		AddFood.requestWindowFeature(Window.FEATURE_NO_TITLE);
		AddFood.setContentView(R.layout.add_food_popup);
		AddFood.setCancelable(true);

		AddFood.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

		Button positiveBtn = (Button) AddFood.findViewById(R.id.positiveBtn);

		positiveBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				AddFood.dismiss();
				TextView title = (TextView) AddFood.findViewById(R.id.foodname_text);
				TextView kcal = (TextView) AddFood.findViewById(R.id.foodkcal_text);
				synchronized (DietplannerPlugin.this) {
					DietplannerPlugin.this.notify();
					try {
						WaitResult.put("title", title.getText());
						WaitResult.put("kcal", kcal.getText());
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});

		AddFood.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				AddFood.dismiss();
				synchronized (DietplannerPlugin.this) {
					DietplannerPlugin.this.notify();
					WaitResult = null;
				}
			}
		});

		AddFood.show();
	}

	public void test() {
		Toast.makeText(MAIN_CONTEXT, " 테스트", Toast.LENGTH_SHORT).show();
	};

	// must be final
	public void testParams(final String arg) {
		Toast.makeText(MAIN_CONTEXT, " 테스트파람" + arg, Toast.LENGTH_SHORT).show();
	};
}
